#include <stdio.h>
#define MAX_LEN (100)

typedef int key_type;                
typedef char info_type;
typedef struct
{
    key_type key;                   
    info_type data;                 
}
rec_type;                           

void create_list(rec_type records[], key_type keys[], int n)
{
    int i;
    for(i = 0; i < n; i++)                  
        records[i].key = keys[i];
}

void disp_list(rec_type records[], int n)
{
    int i;
    for(i = 0; i < n; i++)
        printf("%d ", records[i].key);
    printf("\n");
}

static int bin_search(rec_type records[], int n, key_type key) 
{
    int low = 0;
    int high = n - 1;
    int mid;
    int cnt = 0;
    while(low <= high)
    {
        mid = (low + high) / 2;
        printf("  第%d次比较:在[%d,%d]中比较元素records[%d]:%d\n", ++cnt, low, high, mid, records[mid].key);
        if(records[mid].key == key)                     
            return mid + 1;
        if(records[mid].key > key)
            high = mid - 1;
        else                                         
            low = mid + 1;
    }

    return -1;
}

int main(void)
{
    rec_type records[MAX_LEN];
    int i;
    int n = 10;
    key_type key = 9;
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    create_list(records, a, n);                 
    printf("关键字序列:");
    disp_list(records, n);
    printf("查找%d的比较过程如下:\n", key);
    i = bin_search(records, n, key);
    if(i != -1)
        printf("元素%d的位置是%d\n", key, i);
    else
        printf("元素%d不在表中\n", key);
    return 0;
}